//
//  LiuUserAccountViewModel.swift
//  LiuWeiBo
//
//  Created by 刘晓晨 on 2017/3/29.
//  Copyright © 2017年 刘晓晨. All rights reserved.
//

import UIKit

//Oauth相关接口封装
class LiuUserAccountViewModel: NSObject {

    //单例全局访问点
    static var sharedUserAccountViewModel: LiuUserAccountViewModel = LiuUserAccountViewModel()
    
    //构造函数私有化
    private override init() {
        super.init()
        
        //获取本地归档对象
        userAccount = LiuUserAccount.getUserAccount()
    }
    
    var userAccount:LiuUserAccount?
    
    var isSuccessToken:Bool? {
        if userAccount?.expireDate?.compare(Date()) == ComparisonResult.orderedDescending {
            return true
        } else {
            return false
        }
    }
    
    //获取token
    func requestToken(code:String, finishedCallBack:@escaping (Bool)->()) {
        LiuNetworkManager.sharedTools.requestToken(code: code, compeleteCallBack: { (response, error) in
            if error != nil {
                print("token获取失败error:\(error!)")
                
                //错误回调
                finishedCallBack(false)
                return
            }
            
            //程序执行到此,说明获取token成功
            if let repsonses = response {
                
                //将response强转成字典
                guard let dict:[String:Any] = repsonses as? [String : Any] else {
                    print("接收token时服务器返回非字典")
                    finishedCallBack(false)
                    return
                }
                
                //执行到此,服务器返回的是字典数据
                let userAccount = LiuUserAccount(dict: dict)
                
                self.requestuserMessage(userAccount: userAccount, finishedCallBack:finishedCallBack)
                
            }
        })
    }
    
    //获取用户信息
    fileprivate func requestuserMessage(userAccount:LiuUserAccount, finishedCallBack:@escaping (Bool)->()) {
        //获取到token之后,请求微博用户数据
        LiuNetworkManager.sharedTools.requestUserInfor(userAccount: userAccount, compeleteCallBack: { (response, error) in
            
            if error != nil {
                print("token获取失败error:\(error!)")
                finishedCallBack(false)
                return
            }
            
            if let responseData = response {
                let dict:[String:Any] = responseData as! [String : Any]
                let name = dict["name"] as? String
                let avatarLarge = dict["avatar_large"] as? String
                
                //给模型赋值
                userAccount.name = name
                userAccount.avatar_large = avatarLarge
                
                //给属性赋值
                self.userAccount = userAccount
                //存入沙河
                userAccount.saveUserAccount()
                finishedCallBack(true)
            }
            
        })
    }

    
}
